import { login, logout } from '@/api/user';
import { RESET_STATE, SET_TOKEN } from '@/const/mutationTypes';
import { USER } from '@/const/sessionStoreKeys';

const sessionStore = sessionStorage;

function createUserState() {
  const localUserData = JSON.parse(sessionStore.getItem(USER));
  return (
    localUserData || {
      token: '',
      name: ''
    }
  );
}

const userState = createUserState();

const mutations = {
  [RESET_STATE](state) {
    Object.assign(state, createUserState());
  },
  [SET_TOKEN](state, userInfo) {
    Object.assign(state, userInfo);
  }
};
const actions = {
  async login({ commit }, userInfo) {
    try {
      const res = await login(userInfo);
      const { data, code, message } = res;
      if (code !== 0) {
        return Promise.reject(message);
      }
      commit(SET_TOKEN, data);
      sessionStore.setItem(USER, JSON.stringify(data));

      return Promise.resolve();
    } catch (error) {
      return Promise.reject(error);
    }
  },
  logout({ commit }) {
    return new Promise((resolve, reject) => {
      logout()
        .then(() => {
          sessionStore.clear();
          commit(RESET_STATE);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }
};

export default {
  namespaced: true,
  state: userState,
  mutations,
  actions
};
